/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.authorization.resolver;

import com.bifrost.annotation.CurrentUser;
import com.bifrost.authorization.interceptor.AuthorizationInterceptor;
import com.bifrost.entity.Customer;
import com.bifrost.exception.UnAuthorizationException;
import com.bifrost.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 增加方法注入，将含有CurrentUser注解的方法参数注入当前登录用户
 *
 * @author bifrost
 * @version 1.0.0
 * @Date 2017/10/9 14:38
 * @see CurrentUser
 */
@Component
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    CustomerRepository customerRepository;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //如果参数类型是Customer并且有CurrentUser注解则支持
        if (parameter.getParameterType().isAssignableFrom(Long.class) &&
                parameter.hasParameterAnnotation(CurrentUser.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //取出鉴权时存入的登录用户Id
        Long currentUserId = (Long) nativeWebRequest.getAttribute(AuthorizationInterceptor.UID, RequestAttributes.SCOPE_REQUEST);
        if (currentUserId == null) {
            throw new UnAuthorizationException("用户未登录");
        }
        //从数据库中查询并返回customerRepository.findOne(currentUserId)
        return currentUserId;
    }
}
